﻿/* 
 * author: www.cnblogs.com/luminji
 * date  : 2011/11/18
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Luminji.Core.reflect
{
    public sealed class ReflectHelper
    {
        /// <summary>
        /// find the fieldName, and set a new value
        /// the fied include the instance and public and nonpublic ;
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="fieldName"></param>
        /// <param name="newValue"></param>
        public static void SetFieldToInstance(object instance, string fieldName, object newValue)
        {
            Type t = instance.GetType();
            FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            f.SetValue(instance, newValue);
        }

        /// <summary>
        /// foreach the fromObj properties, and if the toObj have the same property, set it.
        /// include the Instance, public , and nonpublic properties.
        /// </summary>
        /// <param name="fromObj"></param>
        /// <param name="toObj"></param>
        public static void SetPropertiesFromOtherObject(object fromObj, object toObj)
        {
            Type fromObjectType = fromObj.GetType();
            Type toObjectType = toObj.GetType();

            foreach (System.Reflection.PropertyInfo fromProperty in
                fromObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (fromProperty.CanRead)
                {
                    string propertyName = fromProperty.Name;
                    Type propertyType = fromProperty.PropertyType;

                    System.Reflection.PropertyInfo toProperty = toObjectType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    Type toPropertyType = toProperty.PropertyType;

                    if (toProperty != null && toProperty.CanWrite)
                    {
                        object fromValue = fromProperty.GetValue(fromObj, null);
                        //toProperty.SetValue(toProperty, fromValue, null);
                        toProperty.SetValue(toObj, fromValue, null); 
                    }
                }
            } 

        }
    }
}
